package com.kld.common.cardcore;
import com.kld.common.framework.dto.CardExpensePointDTO;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Map;

/**
 * Created by Administrator on 2015/8/26.
 */
public class WebServerUtil {

    /**
     * Logger for this class.
     */
    private static final Logger logger = LoggerFactory.getLogger(WebServerUtil.class);





    private String httpUrl = "https://localhost:8443/global/httpsClientRequest";
    // 客户端密钥库
    private String sslKeyStorePath;
    private String sslKeyStorePassword;
    private String sslKeyStoreType;
    // 客户端信任的证书
    private String sslTrustStore;
    private String sslTrustStorePassword;
    /**
     * 功能描述：使用CXF 请求 HTTP-SOAP 扣减积分
     *
     */
    public String expensePoint(String url, String OperationName, CardExpensePointDTO cardExpensePointDTO) {

       /* System.setProperty("javax.net.ssl.trustStore", "D:/jifenshop/SSL/client/client.truststore");
        System.setProperty("javax.net.ssl.trustStorePassword","111111");
        System.setProperty("javax.net.ssl.keyStoreType","PKCS12") ;
        System.setProperty("javax.net.ssl.keyStore","D:/jifenshop/SSL/client/loyalty.p12") ;
        System.setProperty("javax.net.ssl.keyStorePassword","111111") ;*/
        //String endPoint="https://127.0.0.1:8443/easbCut/services/ApplyFormService";
        logger.info("请求地址 ==> "+url);
        JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();

        Client clientTemp = clientFactory.createClient(url);

        Object[] arg;
        String result = "";
        try {
            Object[] c={cardExpensePointDTO.getCardAsn(),cardExpensePointDTO.getAmount(),cardExpensePointDTO.getUiqueId(),cardExpensePointDTO.getOrgCode(),cardExpensePointDTO.getDetailAmounts(),cardExpensePointDTO.getMAC(),cardExpensePointDTO.getTradeType()};

            arg = clientTemp.invoke(OperationName, c);

            result = (String) arg[0];
        } catch (Exception e) {
            logger.error("webservice扣减积分错误...........");
        }
        return result;



      /*  SSLContext sslContext = null;
        try {
            KeyStore kstore = KeyStore.getInstance("jks");
            kstore.load(new FileInputStream(sslKeyStorePath),
                    sslKeyStorePassword.toCharArray());
            KeyManagerFactory keyFactory = KeyManagerFactory
                    .getInstance("sunx509");
            keyFactory.init(kstore, sslKeyStorePassword.toCharArray());
            KeyStore tstore = KeyStore.getInstance("jks");
            tstore.load(new FileInputStream(sslTrustStore),
                    sslTrustStorePassword.toCharArray());
            TrustManager[] tm;
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance("sunx509");
            tmf.init(tstore);
            tm = tmf.getTrustManagers();
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(keyFactory.getKeyManagers(), tm, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
            SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext);
            Scheme sch = new Scheme("https", 8443, socketFactory);
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();

            nvps.add(new BasicNameValuePair("cardAsn",Long.toString( cardExpensePointDTO.getCardAsn())));
            nvps.add(new BasicNameValuePair("orgCode", cardExpensePointDTO.getOrgCode()));
            nvps.add(new BasicNameValuePair("amount", Long.toString(cardExpensePointDTO.getAmount())));
            nvps.add(new BasicNameValuePair("uiqueId", cardExpensePointDTO.getUiqueId()));
            nvps.add(new BasicNameValuePair("DetailAmounts", cardExpensePointDTO.getDetailAmounts()));
            nvps.add(new BasicNameValuePair("MAC", cardExpensePointDTO.getMAC()));
            nvps.add(new BasicNameValuePair("tradeType",Long.toString( cardExpensePointDTO.getTradeType())));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            String spt = System.getProperty("line.separator");
            BufferedReader buffer = new BufferedReader(new InputStreamReader(
                    httpResponse.getEntity().getContent()));
            StringBuffer stb=new StringBuffer();
            String line=null;
            while((line=buffer.readLine())!=null){
                stb.append(line);
            }
            buffer.close();
            String res=stb.toString();
            System.out.println("result="+res);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }*/
//        return "";
    }



    JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();
    Client clientTemp =null;
    /**
     * 功能描述：使用CXF 请求 HTTP-SOAP 获取扣减积分信息
     * @param url
     * @param OperationName
     * @param uniqueId
     * @return
     */
    public String getExpensePointInfo(String url, String OperationName,String uniqueId) {

        if(clientTemp==null) {
            clientTemp = clientFactory.createClient(url);
        }
        Object[] arg;
        String result = "";
        try {
            Object[] c={uniqueId};
            arg = clientTemp.invoke(OperationName, c);
            result = (String) arg[0];
        } catch (Exception e) {
            logger.error("webservice获取扣减积分信息错误...........");
        }
        return result;
    }


    /**
     * 功能描述：webservice请求请求报文xml格式
     * @param url
     * @param OperationName
     * @param
     * @return
     */
    public String querCardCore(String url, String OperationName,String reqXml) {

        if(clientTemp==null) {
            clientTemp = clientFactory.createClient(url);
        }
        Object[] arg;
        String result = "";
        try {
            arg = clientTemp.invoke(OperationName, reqXml);
            result = (String) arg[0];
        } catch (Exception e) {
            logger.error("webservice错误querCardCore...........");
        }
        return result;
    }



}
